package com.zy.openchat.util;


import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.loader.content.CursorLoader;

import com.zhihu.matisse.filter.Filter;
import com.zy.openchat.App;
import com.zy.openchat.Constants;
import com.zy.openchat.core.model.message.VideoParam;

import java.lang.reflect.Field;
import java.util.List;

import me.bzcoder.mediapicker.SmartMediaPickerex;
import me.bzcoder.mediapicker.config.Constant;
import me.bzcoder.mediapicker.config.MediaPickerEnum;

/**
 * <pre>
 *     author : ch
 *     mail : 1060680253@qq.com
 *     time   : 2018/06/13
 *     desc   : 多媒体工具类
 *     version: 1.0
 * </pre>
 */
public class MediaUtils {

    private static final int max = Integer.MAX_VALUE;
    private static int maxFileSize = max/ Filter.K/Filter.K;

    public static void choosePhotoFg(Fragment context, boolean isShowCapture){
        chooseAlbumFg(context,isShowCapture,1,0);
    }
    public static void chooseAlbumFg(Fragment context,boolean isShowCaptureImage,int maxImageCount,int maxVideoCount){
        context.startActivityForResult(SmartMediaPickerex.builder(context)
                //最大图片选择数目 如果不需要图片 将数目设置为0
                .withMaxImageSelectable(maxImageCount)
                //最大视频选择数目 如果不需要视频 将数目设置为0
                .withMaxVideoSelectable(maxVideoCount)
                //图片选择器是否显示数字
                .withCountable((maxImageCount+maxVideoCount)>0)
                //最大视频长度
                .withMaxVideoLength(30*1000)
                //最大视频文件大小 单位MB
                .withMaxVideoSize(maxFileSize)
                //最大图片高度 默认1920
                .withMaxHeight(max)
                //最大图片宽度 默认1920
                .withMaxWidth(max)
                .capture(isShowCaptureImage)
                .captureAuthority(App.getInstanse().getPackageName() + ".utilcode.fileprovider")
                .captureDirectory(Constants.userImagePath())
                //最大图片大小 单位MB
                .withMaxImageSize(maxFileSize)
                //设置图片加载引擎
                .withImageEngine(new Glide4Engine())
                //前置摄像头拍摄是否镜像翻转图像
                .withIsMirror(false)
                //弹出类别，默认弹出底部选择栏，也可以选择单独跳转
                .withMediaPickerType(MediaPickerEnum.PHOTO_PICKER)
                .build()
                .getIntentForPicker(), Constant.REQUEST_CODE_CHOOSE);
    }

    public static void choosePhoto(FragmentActivity context, boolean isShowCapture){
        chooseAlbum(context,isShowCapture,1,0,30*1000);
    }

    public static void chooseAlbum(FragmentActivity context,boolean isShowCaptureImage,int maxImageCount,int maxVideoCount,int videoMaxLength){
        context.startActivityForResult(SmartMediaPickerex.builder(context)
                //最大图片选择数目 如果不需要图片 将数目设置为0
                .withMaxImageSelectable(maxImageCount)
                //最大视频选择数目 如果不需要视频 将数目设置为0
                .withMaxVideoSelectable(maxVideoCount)
                //图片选择器是否显示数字
                .withCountable((maxImageCount+maxVideoCount)>0)
                //最大视频长度
                .withMaxVideoLength(videoMaxLength)
                //最大视频文件大小 单位MB
                .withMaxVideoSize(maxFileSize)
                //最大图片高度 默认1920
                .withMaxHeight(max)
                //最大图片宽度 默认1920
                .withMaxWidth(max)
                .capture(isShowCaptureImage)
                .captureAuthority(App.getInstanse().getPackageName() + ".utilcode.fileprovider")
                .captureDirectory(Constants.userImagePath())
                //最大图片大小 单位MB
                .withMaxImageSize(maxFileSize)
                //设置图片加载引擎
                .withImageEngine(new Glide4Engine())
                //前置摄像头拍摄是否镜像翻转图像
                .withIsMirror(false)
                //弹出类别，默认弹出底部选择栏，也可以选择单独跳转
                .withMediaPickerType(MediaPickerEnum.PHOTO_PICKER)
                .build()
                .getIntentForPicker(), Constant.REQUEST_CODE_CHOOSE);
    }



    public static List<String> getResultAlbumData(Context context, int requestCode, int resultCode, Intent data){
        return SmartMediaPickerex.getResultData(context, requestCode, resultCode, data);
    }

    static String[] actionArray = new String[]{
            Intent.ACTION_PICK,
            Intent.ACTION_OPEN_DOCUMENT,
            Intent.ACTION_GET_CONTENT,
    };

    /**
     * 启动选择本地图片界面
     *
     * @param activity    启动界面
     * @param requestCode 启动请求码
     */
    public static void startPickImage(@NonNull Activity activity, int requestCode) {
        activity.startActivityForResult(new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI), requestCode);
    }

    /**
     * 启动选择本地图片界面
     *
     * @param fragment    启动界面
     * @param requestCode 启动请求码
     */
    public static void startPickImage(@NonNull Fragment fragment, int requestCode) {
        fragment.startActivityForResult(getPickImageIntent(), requestCode);
    }

    /**
     * 启动选择本地视频界面
     *
     * @param activity    启动界面
     * @param requestCode 启动请求码
     */
    public static void startPickVideo(@NonNull Activity activity, int requestCode) {
        activity.startActivityForResult(getPickVideoIntent(), requestCode);
    }

    public static Intent startPickVideoAndImage() {
//        activity.startActivityForResult(getPickVideoAndImageIntent(), requestCode);
        return pick("*/*",new String[] {"image/*", "video/*"});
    }

    public static final Intent pick(String type, String[] mimeTypes) {

        Intent result = null;

        for (String action : actionArray) {
            if (action.equalsIgnoreCase(Intent.ACTION_PICK)) {
                if (mimeTypes != null && mimeTypes.length > 1) {
                    continue;
                }
            }

            Intent intent = new Intent();

            intent.setAction(action);
            intent.setType(type);

            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            intent.putExtra(Intent.EXTRA_LOCAL_ONLY, false);

            if (mimeTypes != null && mimeTypes.length > 0) {
                intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
            }

            if (action.equalsIgnoreCase(Intent.ACTION_OPEN_DOCUMENT)
                    || action.equalsIgnoreCase(Intent.ACTION_GET_CONTENT)) {
                intent.addCategory(Intent.CATEGORY_OPENABLE);
            }

            try {

//                if (fragment != null) {
//                    fragment.startActivityForResult(intent, requestCode);
//                } else {
//                    context.startActivityForResult(intent, requestCode);
//                }

                result = intent;

                break;

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    /**
     * 启动选择本地视频界面
     *
     * @param fragment    启动界面
     * @param requestCode 启动请求码
     */
    public static void startPickVideo(@NonNull Fragment fragment, int requestCode) {
        fragment.startActivityForResult(getPickVideoIntent(), requestCode);
    }


    /**
     * 根据缩略图路径获取缩略图
     *
     * @param path 缩略图路径
     * @return 返回生成的缩略图
     */
    public static Bitmap getThumbnail(String path) {
        return ThumbnailUtils.createVideoThumbnail(path, MediaStore.Video.Thumbnails.MINI_KIND);
    }

    //复杂版处理  (适配多种API)
    public static String getRealPathFromUri(Context context, Uri uri) {
        int sdkVersion = Build.VERSION.SDK_INT;
        if (sdkVersion < 11) return getRealPathFromUri_BelowApi11(context, uri);
        if (sdkVersion < 19) return getRealPathFromUri_Api11To18(context, uri);
        else return getRealPathFromUri_AboveApi19(context, uri);
    }

    /**
     * 适配api19以上,根据uri获取图片的绝对路径
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    private static String getRealPathFromUri_AboveApi19(Context context, Uri uri) {
        if (DocumentsContract.isDocumentUri(context, uri)) {
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                } else {
                    contentUri = MediaStore.Files.getContentUri("external");
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }


        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * 适配api11-api18,根据uri获取图片的绝对路径
     */
    private static String getRealPathFromUri_Api11To18(Context context, Uri uri) {
        String filePath = null;
        String[] projection = {MediaStore.Images.Media.DATA};
        //这个有两个包不知道是哪个。。。。不过这个复杂版一般用不到
        CursorLoader loader = new CursorLoader(context, uri, projection, null, null, null);
        Cursor cursor = loader.loadInBackground();

        if (cursor != null) {
            cursor.moveToFirst();
            filePath = cursor.getString(cursor.getColumnIndex(projection[0]));
            cursor.close();
        }
        return filePath;
    }

    /**
     * 适配api11以下(不包括api11),根据uri获取图片的绝对路径
     */
    private static String getRealPathFromUri_BelowApi11(Context context, Uri uri) {
        String filePath = null;
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            filePath = cursor.getString(cursor.getColumnIndex(projection[0]));
            cursor.close();
        }
        return filePath;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {
        Cursor cursor = null;
        String column = MediaStore.MediaColumns.DATA;
        String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * 设置视频播放声音
     *
     * @param volume 声音音量（0--1）
     * @param o      播放的对象
     */
    public static void setVolume(float volume, Object o) {
        if (volume < 0 || volume > 1 || o == null) {
            return;
        }
        try {
            Class c = Class.forName("android.widget.VideoView");
            Field field = c.getDeclaredField("mMediaPlayer");
            field.setAccessible(true);
            MediaPlayer mediaPlayer = (MediaPlayer) field.get(o);
            mediaPlayer.setVolume(volume, volume);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @NonNull
    private static Intent getPickImageIntent() {
        return new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    }

    @NonNull
    private static Intent getPickVideoAndImageIntent() {
        Intent intent = new Intent(Intent.ACTION_PICK);
//        //必须加类型，否则会连图片也一起查找到
        intent.setDataAndType(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, MediaStore.Video.Media.CONTENT_TYPE);
        return intent;
    }

    /**
     * 获取选择视频的启动意图
     *
     * @return 返回启动意图
     */
    @NonNull
    private static Intent getPickVideoIntent() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        //必须加类型，否则会连图片也一起查找到
        intent.setDataAndType(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, MediaStore.Video.Media.CONTENT_TYPE);
        return intent;
    }
//
    public static VideoParam getVideoParam(String localPath)
    {
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        try {
            if (!TextUtils.isEmpty(localPath))
            {
                mmr.setDataSource(localPath);
            } else
            {
                //mmr.setDataSource(mFD, mOffset, mLength);
            }

            String duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);//时长(毫秒)
            String width = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);//宽
            String height = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);//高
            String orientation = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
            int widthi = TextUtils.isEmpty(width)?0:Integer.parseInt(width);
            int heighti = TextUtils.isEmpty(height)?0:Integer.parseInt(height);
            int min = Math.min(widthi,heighti);
            int max = Math.max(widthi,heighti);
            if ("90".equals(orientation)) {
                widthi = min;
                heighti = max;
            }
            return new VideoParam(widthi,heighti,TextUtils.isEmpty(duration)?0:Long.parseLong(duration)/1000);
        } catch (Exception ex)
        {
            Constants.Loge("TAG", "MediaMetadataRetriever exception " + ex);
        } finally {
            mmr.release();
        }
        return new VideoParam(0,0,0);
    }
}
